﻿using Digitalmes.Core.Common.Interfaces;
using Digitalmes.Core.Domain.Eitites;
using Digitalmes.Core.Messages;
using Digitalmes.Core.Services;
using ThingsEdge.Contracts;

namespace Digitalmes.Infrastructure.Scada.Handlers;

/// <summary>
/// 转盘转速存档处理器
/// </summary>
internal sealed class RealtimeHandler(
    ITurntableRealtimeService turntableRealtimeService,
    IMessageQueue<TurntableRealtimeMessage> archiveMQ, 
    ILogger<RealtimeHandler> logger) : IScadaNoticeHandler
{
    public async Task HandleAsync(RequestMessage message, CancellationToken cancellationToken = default)
    {
        logger.LogInformation("转台转速数据存档，数据：{@Value}", message.Values.Select(s => new { s.Address, s.Value }));

        var speed = FormatValue(message.Self().GetReal(), 3); // 转速
        TurntableRealtimeRecord input = new()
        {
            ArchiveTime = DateTime.Now,
            RotationalSpeed = speed,
        };
        await turntableRealtimeService.InsertAsync(input, cancellationToken).ConfigureAwait(false);
        await archiveMQ.EnqueueAsync(new TurntableRealtimeMessage(speed), cancellationToken).ConfigureAwait(false);
    }

    private static double FormatValue(double value, int digits)
    {
        return Math.Round(value, digits);
    }
}
